﻿package net.area80.serverside.activity.core
{
	import flash.events.EventDispatcher;
	import net.area80.serverside.errors.ErrorCodes;
	import net.area80.serverside.errors.ErrorDict;
	import net.area80.serverside.events.ServerSideEvent;
	
	/**
	* ...
	* @author Wissarut Pimanmassuriya
	*/
	public class AbstractServerActivity extends EventDispatcher
	{
			/**
		 * Reload data automatically if failed
		 */
		public var reloadIfFailed:Boolean = true;
		/**
		 * Parser is a function for initializing recieves data to a specify object
		 */
		public var parser:Function;
		/**
		 * ErrorCodes object to handle with any error message from server
		 */
		public var errorCodes:ErrorCodes;
		
		
		/**
		 * Use AbstractServerActivity to interact with common http protocol serverside scripting
		 * @param	parser		Parser is a function for initializing recieves data to a specify object
		 * @param	errorCode	ErrorCodes object for defy any error message from server
		 */
		public function AbstractServerActivity (parser:Function = null, errorCodes = null) :void {
				this.parser = parser;
				this.errorCodes = (errorCodes) ? errorCodes : new ErrorCodes();
		}

		/**
		 * Data to send to server
		 * @param	...rest		Arrays of data which format in ["name","data"] or {name:"name", data:"data"}'
		 */
		public function send (...rest):void {
			
		}
		
		/**
		 * Invoked after recieves data from the server
		 * @param	data
		 */
		protected function processData (data:*):void {
			if (data) {
				onSeccess (data);
			} else {
				onError (ErrorDict.CANT_CONNECT_TO_SERVER);
			}
		}
		
		protected function onSeccess (data:*):void {
			dispatchEvent(new ServerSideEvent(ServerSideEvent.ACTIVITY_SUCCESS, null, (parser != null) ? parser(data) : data));
		}
		
		protected function onError (errorCode:String):void {
			dispatchEvent(new ServerSideEvent(ServerSideEvent.ACTIVITY_ERROR, null, ((errorCodes.getErrorMessage(errorCode)) ? errorCodes.getErrorMessage(errorCode) : errorCode) ));
		}
	}
	
}